#include "client.hpp"

Client::Client()
{
    localCertificate = "../client/client-crt.pem";
    privateKey = "../client/client-key.pem";

    start("127.0.0.1", 45434);
}

Client::Client(QString server, quint16 port)
{
    start(server, port);
}

Client::~Client()
{
}

void Client::start(QString server, quint16 port)
{
    // Load private key
    QFile file(privateKey);
    if( !file.open(QIODevice::ReadOnly))
    {
        qDebug() << "Unable to open client private key : " << privateKey;
        return;
    }

    // Passphrase : DefiQt
    QSslKey key(&file, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, "DefiQt");
    file.close();
    client.setPrivateKey(key);

    // Load client's certificate
    client.setLocalCertificate(localCertificate);

    // Load certificate
    if(!client.addCaCertificates( "../ca/ca.pem" ) )
    {
         qDebug() << "Unable to open CA certificate :" << "../ca/ca.pem";
         exit(1);
    }

    // Dont verify server identity
    client.setPeerVerifyMode(QSslSocket::VerifyNone);

    client.ignoreSslErrors();
    connect(&client, SIGNAL(encrypted()), this, SLOT(connection()));
    client.connectToHostEncrypted(server, port);
}

void Client::connection()
{
    client.write("Hello server\r\n");

    // Load client's GUI
    //Test *testGUI = new Test();
}
